<template>
	<view class="components-app-map">
		<view id="components-app-map" @click="tmap.onClick" :prop="location" :change:prop="tmap.updateEcharts"></view>
	</view>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import { debounce } from '@/common/utils';
import { getMapKey,getLocation } from '@/common/utils/map';
import { getMapKey as getMapKeyD } from '@/common/request/api'
export default defineComponent({
	props: { longitude: Number, latitude: Number, userLongitude: Number, userLatitude: Number, autoLocation: Boolean },
	data() {
		return {
			markerList: [],
			dataIndex: 0
		};
	},
	computed: {
		location() {
			return {
				longitude: this.longitude,
				latitude: this.latitude
			};
		},
		userLocation() {
			return {
				longitude: this.userLongitude || this.longitude,
				latitude: this.userLatitude || this.latitude
			};
		}
	},
	// created() {
	// 	this.$nextTick(() => {
	// 		this.getMapData()
	// 	})
	// },
	methods: {
		// 地图数据获取
		getMapData() {
			this.markerList = [
				{
					lng: 116.388771,
					lat: 39.928242
				},
				{
					lng: 116.392157,
					lat: 39.930482
				},
				{
					lng: 116.389219,
					lat: 39.925809
				}
			];
		},
		getKey(cb) {
			getMapKeyD().then(res => {
				cb(res)
			})
			// getMapKey().then(res => cb(res));
		},
		//图表点击回调事件
		onViewClick(params) {},
		onMarkerClick(marker) {
			this.$emit('markerClick', marker);
		},
		onMapPan: debounce(function (location, cb) {
			this.$emit('mapPan', location, cb);
		}, 1000),
		getMarkerArray(cb) {
			this.$emit('getMarkerArray', cb);
		},
		mapLocationChange(location, cb) {
			this.$emit('mapLocationChange', location, cb);
		},
		getLocation() {
			return new Promise((resolce, reject) => {
				getLocation(this.$t('nearby.openGPS'), this.$t('nearby.GPSErr'))
					.then((res) => {
						this.$emit('updateLocation', res, () => {
							resolce();
						});
					})
					.catch(() => {
						reject();
					});
			});
		}
	}
});
</script>

<script module="tmap" lang="renderjs">

import {
	debounce
} from '@/uni_modules/endless-ui/libs/utils/lodash'
import {
	TMAP_OPTION
} from "../env"
export default {
	data() {
		return {
			map: null,
			ownerInstanceObj: null, //service层对象
			markerLayer: [],
			labelLayer:[],
			dataIndex: null,
			// 地图当前中心点的定位，用与记录地图平移后的位置
			mpaLocation: {},
			// 大头针标记
			pinMarker: null,
			isPinMove:false
		}
	},
	mounted() {
		this.getKey(res => {
			const mapkey = res.data.key[0]
			const $MapKeyType = res.data.keyType
			if ($MapKeyType === '1') {
				if (window.qq && window.qq.maps && window.qq.maps.LatLng) {

					this.initAmap()
				} else {
					const script = document.createElement('script')
					window.tMapInit = () => {
						this.initAmap()
					}
					script.src = 'https://map.qq.com/api/js?v=2.exp&key=' +mapkey + '&callback=tMapInit'
					// script.onload = this.initAmap.bind(this)
					document.head.appendChild(script)
				}
			} else {

				if (window.google && window.google.maps) {

					this.initAmap()
				} else {
					const script = document.createElement('script')
					window.gMapInit = () => {
						this.initGmap()
					}

					script.src = 'https://maps.googleapis.com/maps/api/js?key=' +mapkey +
						'&callback=gMapInit&libraries=&v=weekly'
					document.head.appendChild(script)
				}

			}

		})
		uni.$on('updateMapCenter',data => {
			this.isPinMove = true
			const newCenter = new qq.maps.LatLng(data.lat, data.lng);
			this.map.setCenter(newCenter);
		})

	},
	methods: {
		initAmap() {
			//定义地图中心点坐标
			//定义map变量，调用 qq.maps.Map() 构造函数创建地图
			this.map = new qq.maps.Map(document.getElementById("components-app-map"), {
				center: new qq.maps.LatLng(this.location.latitude, this.location.longitude), //设置地图中心点坐标
				...TMAP_OPTION.option,
				...this.getTmapControlOption()
			});
			if (TMAP_OPTION.locationControl.show) {
				this.setLocationControl()
			}
			if (TMAP_OPTION.pin.show) {
				const pinMarker = new qq.maps.Marker({
					position: new qq.maps.LatLng(this.location.latitude, this.location.longitude),
					map: this.map
				});
				pinMarker.setIcon(this.createdIcon(TMAP_OPTION.pin.style));
				this.pinMarker = pinMarker
				this.onPan()
			}
			// this.setTmapControl()
			this.initMapSuccess()

		},
		initGmap () {
			this.map = new google.maps.Map(document.getElementById("components-app-map"), {
				center: new google.maps.LatLng(this.location.latitude, this.location.longitude), //设置地图中心点坐标
				...TMAP_OPTION.option,
				...this.getGmapControlOption()
			});
			this.initMapSuccess()
		},
		async initMapSuccess () {
			if(this.autoLocation){
				await this.getLocation()
			}
			this.initMarkers()
		},
		// 设置定位控件
		setLocationControl() {
			const customControls = document.createElement("div");
			customControls.style.cssText = "padding-right:20px";
			const customControlsBox = document.createElement("div");
			customControlsBox.style.cssText =
				"padding:6px;border-radius:100%;background:#ffffff;display: flex;align-items: center;justify-content: center;";
			customControls.index = 1; //设置在当前布局中的位置
			const controlsIcon = document.createElement("img");
			controlsIcon.style.cssText =
				`width:${TMAP_OPTION.locationControl.width}px;height:${TMAP_OPTION.locationControl.height}px;`;
			controlsIcon.src = TMAP_OPTION.locationControl.icon
			customControlsBox.appendChild(controlsIcon)
			customControls.appendChild(customControlsBox)
			this.map.controls[qq.maps.ControlPosition[TMAP_OPTION.locationControl.position]].push(customControls);
			qq.maps.event.addDomListener(customControls, 'click', () => {
				this.map.panTo(new qq.maps.LatLng(this.userLocation.latitude, this.userLocation.longitude));
			});

		},
		createdIcon(option) {
			return new qq.maps.MarkerImage(
				option.src,
				new qq.maps.Size(option.width, option.height),
				new qq.maps.Point(...option.origin),
				new qq.maps.Point(...option.anchor),
			)
		},
		getTmapControlOption() {
			const control = TMAP_OPTION.control
			const option = {
				scaleControl: control.scale.show,
				zoomControl: control.scale.show,
				panControl: control.pan.show,
				mapTypeControlOptions: {
					mapTypeIds: control.mapType.ids.map(item => qq.maps.MapTypeId[item]),
					position: qq.maps.ControlPosition[control.mapType.position]
				}
			}
			if (control.scale.show) {
				option['scaleControlOptions'] = {
					position: qq.maps.ControlPosition[control.scale.position]
				}
			}
			if (control.zoom.show) {
				option['zoomControlOptions'] = {
					position: qq.maps.ControlPosition[control.zoom.position]
				}
			}
			if (control.pan.show) {
				option['panControlOptions'] = {
					position: qq.maps.ControlPosition[control.pan.position]
				}
			}
			return option
		},
		getGmapControlOption () {
			const control = TMAP_OPTION.control
			const option = {
				scaleControl: control.scale.show,
				zoomControl: control.scale.show,
				mapTypeControl: false,
				streetViewControl: false,
				rotateControl: false,
				fullscreenControl: false
			}
			return option
		},

		onPan() {
			//监听地图移动，不要监听鼠标拖动，否则调用panTo设置地图中心点时，不会触发监听事件
			qq.maps.event.addDomListener(this.map, "center_changed", debounce(() => {

				//获取地图中心点
				let position = this.map.getCenter();
				// 记录当前位置
				this.mpaLocation = {
					latitude: position.lat,
					longitude: position.lng
				}
				if (!this.isPinMove) {
					this.onMapPan(this.mpaLocation, (option) => {
						if (option.marker) {
							this.setMarkers(option.marker)
						}
					})
				} else {
					this.isPinMove = false
				}


				if (TMAP_OPTION.pin.show) {

					this.pinMarker.setPosition(new qq.maps.LatLng(this.mpaLocation.latitude, this
						.mpaLocation.longitude))
				}

			}, TMAP_OPTION.pin.debounceTime));
		},
		//初始化标记点
		initMarkers() {
			if (!this.map) {
				return
			}
			this.getMarkerArray((markerArray,defaultMarker = true) => {
				this.setMarkers(markerArray,defaultMarker)

			})



		},
		setMarkers(markerArray,defaultMarker) {
			this.markerLayer.forEach(item => {
				item.setMap(null)
			})
			this.labelLayer.forEach(item => {
				item.setMap(null)
			})
			this.markerLayer.splice(0)
			this.labelLayer.splice(0)
		
			markerArray.forEach((item) => {
				const position = new qq.maps.LatLng(item.latitude, item.longitude)
				const marker = new qq.maps.Marker({
					position ,
					map: this.map,
					id:item.id
				});
				let style = defaultMarker ? TMAP_OPTION.markerStyle[item.icon]:{
					src:item.iconPath,
					width:item.width,
					height:item.height,
					origin:[0, 0],
					anchor:item.anchor||[0, 0]
				}
		
				marker.setIcon(this.createdIcon(style));
				if(item?.callout?.content||item.title){
					const label = new qq.maps.Label({
					                position,
					                map: this.map,
					                content: item?.callout?.content||item.title,
									offset:new qq.maps.Size(0, (-item.height/2)-8),
									id:item.id
					 });
					 qq.maps.event.addDomListener(label, "click", e => {
					 	this.onMarkerClick(e.target.id)
					 });
					 this.labelLayer.push(label)
				}
				qq.maps.event.addDomListener(marker, "click", e => {
					this.onMarkerClick(e.target.id)
				});
				this.markerLayer.push(marker)
			})
		},
		updateEcharts(newValue, oldValue, ownerInstance, instance) {
			// 监听 service 层数据变更
			this.ownerInstanceObj = ownerInstance
			this.initMarkers()
		},
		onClick(event, ownerInstance) {
			// 调用 service 层的方法
			ownerInstance.callMethod('onViewClick', {
				dataIndex: this.dataIndex
			})
		}
	}
}
</script>

<style lang="scss" scoped>
.components-app-map {
	width: 100%;
	height: 100%;

	#components-app-map {
		width: 100%;
		height: 100%;
	}
}
</style>
